<template>
  <div>
    <el-row style="margin-bottom: 10px">
      <div style="margin-left: 20px">
        <span style="font-size: 16px; font-weight: bold;">{{ customer.name }}</span>
        <span style="font-size: 16px; font-weight: bold;margin-left: 10px">|{{ customer.crmcustomercategory__name }}</span>
        <div style="display: block;">
          <el-tag v-for="(item, index) in customer.tag" :key="item" effect="dark" :color="getBackgroundColor(index)" size="mini" style="margin-right: 5px">{{ item }}</el-tag>
        </div>

      </div>
      <div style="margin-left: 20px">
        <span @click="ShoweditCRMCustomer"><svg-icon v-if="customer.country" :icon-class="customer.country" />{{ getCountryLabel(customer.country) }}<el-icon class="el-icon-edit" /></span>
      </div>
    </el-row>
    <el-row>
      <el-tabs type="border-card">
        <el-tab-pane label="动态">
          <div style="height: 520px;overflow-y: auto;">
            <el-form v-if="customer.id !== ''" size="mini" :model="remark_temp" label-position="top" style="line-height: 1px;">
              <el-form-item label="跟进消息">
                <!--                      <el-tag type="info" size="mini" @click="remark_temp.content += item.tag_name" :key="item.tag_name" v-for="item in tags">{{item.tag_name}}</el-tag>-->
                <el-input
                  v-model="remark_temp.content"
                  type="textarea"
                  :rows="inputRows"
                  @focus="handleFocus"
                  @blur="handleBlur"
                />
              </el-form-item>
              <el-form-item label="下次跟进日期">
                <el-date-picker
                  v-model="remark_temp.next_follow_up_time"
                  align="right"
                  type="datetime"
                  placeholder="选择日期"
                  value-format="timestamp"
                  :picker-options="pickerOptions"
                />
                <el-button size="mini" type="primary" @click="handleSaveRemark">保存</el-button>
              </el-form-item>
            </el-form>
            <el-divider />
            <div v-for="(item,index) in remarks" :key="index" style="margin-bottom: 10px; background-color: #fde2e2; box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);">
              <div style="padding: 10px; display: flex; align-items: center; justify-content: space-between;">
                <div>
                  <span style="margin-right: 5px; font-weight: bold;">{{ item.creator_name }}</span>
                  <span v-if="item.next_follow_up_time_str !== ''" style="color: #606266;">跟进日期: {{ item.next_follow_up_time_str }}</span>
                </div>
                <el-button type="text" icon="el-icon-delete" style="color: #F56C6C;" @click="handleDeleteRemark(item)" />
              </div>
              <div style="padding: 0 10px 10px 10px;">
                <pre style="margin: 0; white-space: pre-wrap; word-wrap: break-word;">{{ item.content }}</pre>
              </div>
              <div style="padding: 5px 10px; text-align: right; color: #909399; font-size: 12px;">
                {{ item.create_at }}
              </div>
            </div>

            <div>
              <h3>订单列表:</h3>
              <div v-for="(item,index) in orders" :key="index">
                <div style="display: block">
                  <a :href="'https://erp.kikimami.com/#/crm/crmorder?kw=' + item.order_no" target="_blank">[{{ item.order_no }}]{{ item.name }}</a>
                  <span style="display: block"><el-tag effect="dark" size="mini" :color="item.crmorderstate_color">{{ item.crmorderstate_name }}</el-tag></span>
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane :label="'邮件(' + mails.length + ')'">
          <div style="height: 520px;overflow-y: auto;">
            <el-timeline style="padding-left: 1px;">
              <el-timeline-item v-for="(mail, index) in mails" :key="index" :type="mail.mail_from !== customer.mail ? 'success':'danger'" :timestamp="mail.short_from + '(' + mail.mail_date_short + ')'" placement="top">
                <el-card shadow="hover">
                  <p>{{ mail.short_content }}</p>
                  <el-link type="primary" style="float: right;" @click="handleShowMail(mail)">查看内容</el-link>
                </el-card>
              </el-timeline-item>
            </el-timeline>
          </div>
        </el-tab-pane>
        <el-tab-pane :label="'聊天(' + whatsappmessages.length + ')'">
          <div style="height: 520px;overflow-y: auto;">
            <div v-for="msg in whatsappmessages" :key="msg.id" class="message">
              <div v-if="msg.message_from !== customer.whatsapp" class="my-message">
                <div class="message-body">
                  <!-- 音频消息 -->
                  <div v-if="msg.content_type.includes('audio')">
                    <audio :src="msg.media_url" controls />
                  </div>
                  <!-- 图片消息 -->
                  <div v-else-if="msg.content_type.includes('image')">
                    <el-image
                      style="max-width: 300px; height: auto;"
                      :src="msg.media_url"
                      :preview-src-list="[msg.media_url]"
                    />
                  </div>
                  <!-- 文本消息 -->
                  <div v-else>{{ msg.body }}</div>
                </div>
                <div class="message-time">{{ msg.message_at }}</div>
                <div v-if="msg.sending" class="message-status">正在发送...</div>
              </div>
              <div v-else class="their-message">
                <div class="message-body">
                  <!-- 音频消息 -->
                  <div v-if="msg.content_type.includes('audio')">
                    <audio :src="msg.media_url" controls />
                  </div>
                  <!-- 图片消息 -->
                  <div v-else-if="msg.content_type.includes('image')">
                    <el-image
                      style="max-width: 300px; height: auto;"
                      :src="msg.media_url"
                      :preview-src-list="[msg.media_url]"
                    />
                  </div>
                  <!-- 文本消息 -->
                  <div v-else>
                    <div class="original-message">{{ msg.body }}</div>
                    <!-- 翻译文本 -->
                    <div v-if="msg.body_translate" class="translated-message">{{ msg.body_translate }}</div>

                  </div>
                </div>
                <div class="message-time">{{ msg.message_at }}<a v-if="msg.body_translate === ''" style="font-size: 12px;color:#2f2ff7;" @click="translateMessage(msg)">翻译</a></div>
              </div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane :label="attachments_label">
          <el-row style="height: 520px;overflow-y: auto;">
            <crmfilesmanager color="#1890ff" class="editor-upload-btn" @insert="handleInsertFile" />
            <el-divider />
            <div v-for="(item,index) in attachments" :key="index" style="margin-bottom: 5px">
              <el-image
                v-if="item.crmfile_data.content_type.indexOf('image') !== -1"
                style="width: 100px; height: auto;"
                :src="item.crmfile_data.url"
                :preview-src-list="[item.crmfile_data.url]"
              />
              <el-link v-else :href="item.crmfile_data.url" target="_blank">{{ item.crmfile_data.filename }}</el-link>
            </div>
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </el-row>
    <el-dialog
      :visible.sync="showMialBodyVisible"
      append-to-body
      title="查看邮件内容"
      width="1080px"
      @close="handleCloseShowMail"
    >
      <div style="display: block;">
        主 题:<el-input v-model="showmail.subject" />
      </div>
      <div style="display: block;">
        发件人:<el-input v-model="showmail.mail_from" />
      </div>
      <div style="display: block;">
        收件人:<el-input v-model="showmail.mail_to" />
      </div>
      <div style="display: block; margin-top: 5px;" />
      <iframe v-if="showmail.content_type === 'text/html'" ref="iframe" style="border: none; max-height: 400px;" :src="showmail.iframeSrc" width="100%" height="400" />
      <div v-else style="display: inline-block;background-color: aliceblue;"><pre style="overflow: scroll;white-space: pre-wrap;">{{ showmail.body }}</pre></div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showMialBodyVisible = false;">取 消</el-button>
      </span>
    </el-dialog>
    <crmeditcustomer
      :customer_row="customer"
      :doaction="action"
      :is-visible="editCustomerVisible"
      @close="editCustomerVisible=false"
    />
  </div>
</template>

<script>
import { countries, getCountryLabel, getBackgroundColor } from '../../../api/crm/crmcommon'
import { Get as GetRemark, Post, Get as GetTags, Delete } from '@/api/crm/crmm'
import { Get as GetCustomer } from '@/api/crm/crmcustomer'
import crmtinymce from '@/components/CRMTinymce'
import { GetBody } from '@/api/crm/crmmailbox'

import qs from 'qs'
import Crmeditcustomer from './crmeditcustomer'
import Crmfilesmanager from '../../../components/crmfilesmanager'

export default {
  name: 'Crmcustomerinfocard',
  components: { Crmfilesmanager, Crmeditcustomer, crmtinymce },
  props: ['customer_id'],
  data() {
    return {
      editCustomerVisible: false,
      showMialBodyVisible: false,
      showmail: {
        mailbox_id: '',
        text_content: '',
        body: '',
        subject: '',
        send_account: '',
        mail_from: '',
        iframeSrc: '',
        mail_to: ''
      },
      action: 'edit',
      customer: {
        id: '',
        name: '',
        country: '',
        remarks: [],
        mails: [],
        attachments: []
      },
      getCountryLabel: getCountryLabel,
      getBackgroundColor: getBackgroundColor,
      remark_temp: {
        content: '',
        next_follow_up_time: '',
        crmcustomer_id: ''
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() <= Date.now() - 8.64e7
        }
      },
      inputRows: 3,
      tags: [],
      remarks: [],
      orders: [],
      mails: [],
      whatsappmessages: [],
      attachments: [],
      attachments_label: '附件',
      countries: countries
    }
  },
  watch: {
    customer_id: {
      handler(v) {
        this.reset_data()
        if (v !== undefined && v !== '') {
          this.handleGetCustomer()
        }
      },
      immediate: true // 立即触发一次handler函数
    }
  },
  created() {
    // 获取tags
    this.handleGetTags()
  },
  methods: {
    handleInsertFile(item) {
      console.log(item)
      const temp = {
        'table_name': 'CRMCustomerFile',
        'crmcustomer_id': this.customer.id,
        'crmfile_id': item.id
      }
      Post(temp).then(response => {
        this.$notify({
          title: '成功',
          message: '添加成功',
          type: 'success',
          duration: 1000
        })
        temp['crmfile_data'] = item
        this.attachments.push(temp)
      })
    },
    handleDeleteRemark(item) {
      item.table_name = 'CRMRemark'
      Delete(item.id, item).then(response => {
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 1000
        })
        // 从this.remarks中删除
        this.remarks = this.remarks.filter(v => v.id !== item.id)
      })
    },
    ShoweditCRMCustomer() {
      this.editCustomerVisible = true
    },
    handleFocus() {
      this.inputRows = 4 // 获得焦点时行数变为4
    },
    handleBlur() {
      if (this.remark_temp.content === '') {
        this.inputRows = 1 // 失去焦点且内容为空时行数重置为1
      }
    },
    handleSaveRemark() {
      if (this.customer.id) {
        this.remark_temp.crmcustomer_id = this.customer.id
        this.remark_temp.table_name = 'CRMRemark'
        Post(this.remark_temp).then(response => {
          this.$notify({
            title: '成功',
            message: '添加成功',
            type: 'success',
            duration: 1000
          })
          this.handleGetRemarks()
        })
      }
    },
    reset_data() {
      this.customer = {
        id: '',
        name: '',
        country: '',
        remarks: [],
        mails: [],
        attachments: [],
        whatsappmessages: []
      }
      this.remark_temp = {
        content: '',
        next_follow_up_time: '',
        crmcustomer_id: ''
      }
      this.remarks = []
      this.orders = []
      this.mails = []
      this.attachments = []
      this.whatsappmessages = []
    },
    handleGetCustomer() {
      if (this.customer_id) {
        console.log('get customer', this.customer_id)
        GetCustomer(this.customer_id, qs.stringify({ 'm': 1, 'o': 1 })).then(response => {
          this.customer = response.data
          this.remarks = this.customer.remarks
          this.mails = this.customer.mails
          this.orders = this.customer.orders
          this.attachments = this.customer.attachments
          this.whatsappmessages = this.customer.whatsappmessages
          this.$emit('get-customer', this.customer)
        }).catch(err => {
          console.log(err)
        })
      }
    },
    handleGetRemarks() {
      this.remarks = []
      GetRemark(null, qs.stringify({
        table_name: 'CRMRemark',
        crmcustomer_id: this.customer.id,
        page: 1,
        pagesize: 100
      })).then(response => {
        this.remarks = response.data.data
      }).catch(err => {
        console.log(err)
      })
    },
    handleGetTags() {
      GetTags(null, qs.stringify({
        table_name: 'CRMTag',
        page: 1,
        app: 'mail',
        pagesize: 100
      })).then(response => {
        this.tags = response.data.data
      }).catch(err => {
        console.log(err)
      })
    },
    fetchEmailBody(mail) {
      mail.body = null
      GetBody(qs.stringify({
        mail_token: mail.mail_token
      }))
        .then(response => {
          // 确保response是字符串形式的HTML内容
          // 或者如果response是一个对象，你可能需要 response.data 或类似的属性
          // 添加缺失的DOCTYPE声明、<html>、<body>标签
          this.showmail.body = response
          const fullHtmlContent = `<!DOCTYPE html><html><body style="background-color: aliceblue;">${response}</body></html>`

          // 创建一个Blob对象，类型为"text/html"
          const blob = new Blob([fullHtmlContent], { type: 'text/html' })
          // 创建一个指向该Blob的URL
          mail.iframeSrc = URL.createObjectURL(blob)
          this.showmail.iframSrc = mail.iframeSrc
          this.showMialBodyVisible = true
        }).catch(err => {
          console.log(err)
        })
    },
    handleShowMail(mail) {
      this.showmail = mail
      console.log(this.showmail)
      if (mail.body === null || mail.body === '') {
        this.fetchEmailBody(mail)
      } else {
        this.showMialBodyVisible = true
      }
    },
    handleCloseShowMail() {
      if (this.$refs.showmailty) {
        this.$refs.showmailty.$destroy()
      }
    }
  }
}
</script>

<style>
/* 添加消息样式 */
.message {
  display: flex;
  margin-bottom: 10px;
}

.my-message {
  margin-left: auto;
  padding: 10px;
  background-color: #dcf8c6; /* 浅绿色，表示自己的消息 */
  border-radius: 5px;
  text-align: right;
}

.their-message {
  margin-right: auto;
  padding: 10px;
  background-color: #fff; /* 白色，表示对方的消息 */
  border-radius: 5px;
  text-align: left;
}

.message-body {
  margin-bottom: 5px;
}

.message-time {
  font-size: 0.75rem;
  color: #999;
}
.el-drawer__header {
  margin-bottom: 1px;
}
</style>
